package com.wenbing.miio.mi.device.remote;

import com.wenbing.miio.core.*;
import com.wenbing.miio.core.exception.NetworkLayerException;
import com.wenbing.miio.mi.MessageFrame;
import com.wenbing.miio.mi.MiFrameLayer;
import com.wenbing.miio.mi.MiDeviceUtil;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * @author wen bing
 * @projectName: miio
 * @package: com.wenbing.miio.mi.device
 * @className: Layer
 * @date 2024/09/20 15:39
 **/

public class ClientModeAdapterLayer extends AbstractShareContextNetworkLayer {

    @Override
    protected ByteBuffer unpacking(NetworkLayerContext context, ByteBuffer packingData) throws IOException, NetworkLayerException {
        return packingData;
    }

    @Override
    protected void deliverLowerLayer(NetworkLayerContext context, ByteBuffer packingData) throws NetworkLayerException, IOException {
        int flags = context.getAttribute(MiFrameLayer.ATTR_FLAGS,0);
        // 丢弃收到的hello请求
        if (flags == MessageFrame.FLAGS_HELLO) {
            LOGGER.debug("drop the hello package");
            return;
        }
        int did = context.getAttribute(MiFrameLayer.ATTR_DID);
        if (did != MiDeviceUtil.getDeviceId(this)) {
            throw new NetworkLayerException("did not match");
        }
        super.deliverLowerLayer(context, packingData);
    }

    @Override
    protected ByteBuffer packing(NetworkLayerContext context, ByteBuffer packingData) throws IOException, NetworkLayerException {
        int did = MiDeviceUtil.getDeviceId(this);
        context.setAttribute(MiFrameLayer.ATTR_DID, did);
        long time = MiDeviceUtil.getRunningTime(this);
        context.setAttribute(MiFrameLayer.ATTR_TIMESTAMP, time);
        return packingData;
    }
    @Override
    protected void deliverUpperLayer(NetworkLayerContext context, ByteBuffer packingData) throws NetworkLayerException, IOException {
        int flags = context.getAttribute(MiFrameLayer.ATTR_FLAGS,0);
        // 单独处理hello包
        if (flags == MessageFrame.FLAGS_HELLO) {
            LOGGER.debug("reset the hello package did");
            context.setAttribute(MiFrameLayer.ATTR_DID, 0xffffffff);
        }
        super.deliverUpperLayer(context, packingData);
    }

}
